package com.zbkj.crmeb.user.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.crmeb.core.common.CommonResult;
import com.crmeb.core.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.utils.IdCardUtils;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.MerchantAddress;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.service.MerchantAddressService;
import com.zbkj.crmeb.front.request.UserAddressRequest;
import com.zbkj.crmeb.system.model.SystemCity;
import com.zbkj.crmeb.system.service.SystemCityService;
import com.zbkj.crmeb.user.dao.UserAddressDao;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.model.UserAddress;
import com.zbkj.crmeb.user.service.UserAddressService;
import com.zbkj.crmeb.user.service.UserService;

/**
 * @author Mr.Zhang
 * @Description UserAddressServiceImpl 接口实现
 * @since 2020-04-28
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressDao, UserAddress> implements UserAddressService {
    @Resource
    private UserAddressDao userAddressDao;
    @Autowired
    private SystemCityService systemCityService;
    @Autowired
    private UserService userService;
    @Autowired
    private MerchantAddressService merchantAddressService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private IdCardUtils idCardUtils;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 列表
     *
     * @return List<UserAddress>
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public List<UserAddress> getList(PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return userAddressDao.selectList(lambdaQueryWrapper);
    }

    /**
     * 根据基本题条件查询
     *
     * @param address 查询条件
     * @return 结果地址
     */
    @Override
    public UserAddress getUserAddress(UserAddress address) {
        LambdaQueryWrapper lq = new LambdaQueryWrapper();
        lq.setEntity(address);
        return userAddressDao.selectOne(lq);
    }

    /**
     * 创建地址
     *
     * @param request UserAddressRequest 参数
     * @return List<UserAddress>
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public UserAddress create(UserAddressRequest request) {
        Integer uid = userService.getUserIdException();
        User user = userService.getById(uid);
        ChannelMerchant channelMerchant = channelMerchantService.getById(user.getMerId());
        UserAddress userAddress = new UserAddress();
        //身份证认证
        if (StringUtils.isNotBlank(request.getIdCard()) && channelMerchant.getChannelType() != 8) {
            idCardUtils.checkIdCard(StringUtils.defaultString(request.getIdName(),request.getRealName()), request.getIdCard());
        }
        BeanUtils.copyProperties(request, userAddress);
        userAddress.setCity(request.getAddress().getCity());
        userAddress.setCityId(request.getAddress().getCityId());
        userAddress.setDistrict(request.getAddress().getDistrict());
        userAddress.setProvince(request.getAddress().getProvince());
        userAddress.setRegion(request.getAddress().getRegion());
        if (request.getAddress() != null && request.getAddress().getCityId() != null
                && request.getAddress().getCityId() > 0
                && StringUtils.isNotBlank(request.getAddress().getCity())) {
            checkCity(userAddress.getCityId());
        }
        userAddress.setUid(userService.getUserIdException());
        if (userAddress.getIsDefault()) {
            //把当前用户其他默认地址取消
            cancelDefault(userAddress.getUid());
        }
        saveOrUpdate(userAddress);
        return userAddress;
    }

    /**
     * 设置默认
     *
     * @param id Integer id
     * @return UserAddress
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public boolean def(Integer id) {
        //把当前用户其他默认地址取消
        cancelDefault(userService.getUserIdException());
        UserAddress userAddress = new UserAddress();
        userAddress.setId(id);
        userAddress.setUid(userService.getUserIdException());
        userAddress.setIsDefault(true);
        return updateById(userAddress);
    }

    /**
     * 删除
     *
     * @param id Integer id
     * @return UserAddress
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public boolean delete(Integer id) {
        //把当前用户其他默认地址取消
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getId, id);
        lambdaQueryWrapper.eq(UserAddress::getUid, userService.getUserIdException());
        userAddressDao.delete(lambdaQueryWrapper);
        return true;
    }

    /**
     * 获取默认地址
     *
     * @return UserAddress
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public UserAddress getDefault() {
        //把当前用户其他默认地址取消
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getIsDefault, true);
        lambdaQueryWrapper.eq(UserAddress::getUid, userService.getUserId());
        return userAddressDao.selectOne(lambdaQueryWrapper);
    }

    @Override
    public UserAddress getById(Integer addressId) {
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getId, addressId);
        return userAddressDao.selectOne(lambdaQueryWrapper);
    }


    /**
     * 根据地址参数获取用户收货地址
     *
     * @param userAddress
     * @param pageParamRequest
     * @return
     */
    @Override
    public List<UserAddress> getListByUserAddress(UserAddress userAddress, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.setEntity(userAddress);
        if (CollectionUtils.isNotEmpty(userAddress.getAreaTypes())) {
            lambdaQueryWrapper.in(UserAddress::getAreaType, userAddress.getAreaTypes());
        }
        return userAddressDao.selectList(lambdaQueryWrapper);
    }

    /**
     * 根据区域获取自提地址
     *
     * @param areaType
     * @param merId
     * @return
     */
    @Override
    public Object getTakeAddress(List<Integer> areaType, Integer merId) {
        if (CollectionUtils.isEmpty(areaType)) {
            throw new CrmebException("区域类型不能为空");
        }
        ChannelMerchant channelMerchant = Optional.ofNullable(channelMerchantService.getById(merId)).orElse(new ChannelMerchant());
        if (Objects.equals(channelMerchant.getIsTake(), 0)) {
            return null;
        }
        //TODO mod by cdm 2023/06/27 改成多条
        return merchantAddressService.list(Wrappers.<MerchantAddress>lambdaQuery().eq(MerchantAddress::getStatus, 1).
                eq(MerchantAddress::getMerId, merId).in(MerchantAddress::getAreaType, areaType));
        /*return merchantAddressService.getOne(Wrappers.<MerchantAddress>lambdaQuery().eq(MerchantAddress::getStatus,1)
                .eq(MerchantAddress::getMerId, merId).in(MerchantAddress::getAreaType, areaType).last("LIMIT 1"));*/
    }

    @Override
    public CommonResult<String> verifyIdCard(UserAddressRequest request) {
        String idName = request.getIdName();
        String idCard = request.getIdCard();
        if (StringUtils.isAnyBlank(idName,idCard)){
            return CommonResult.failed("支付人信息不能为空");
        }
        String key = idName+"_"+idCard;
        Object obj = redisUtil.get(key);
        if (null != obj){
            return CommonResult.success(String.valueOf(idCard));
        }
        try {
            idCardUtils.checkIdCard(idName, idCard);
            // 默认存两个月
            redisUtil.set(key, idCard, 60L, TimeUnit.DAYS);
            return CommonResult.success(idCard);
        }catch (CrmebException e){
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 检测城市id是否合法
     *
     * @param cityId Integer 城市id
     * @author Mr.Zhang
     * @since 2020-04-30
     */
    private void checkCity(Integer cityId) {
        //检测城市Id是否存在
        SystemCity systemCity = systemCityService.getCityByCityId(cityId);
        if (systemCity == null) {
            throw new CrmebException("请选择正确的城市");
        }
    }

    /**
     * 取消默认地址
     *
     * @param userId Integer 城市id
     * @author Mr.Zhang
     * @since 2020-04-30
     */
    private void cancelDefault(Integer userId) {
        //检测城市Id是否存在
        UserAddress userAddress = new UserAddress();
        userAddress.setIsDefault(false);
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getUid, userId);
        update(userAddress, lambdaQueryWrapper);
    }

}

